package com.haungg.user;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tree.HashTree;
import tree.TreeNode;
import tree.TreeObject;

import com.haungg.base.BaseServiceImpl;
import com.haungg.po.TMenu;
import com.haungg.po.TUser;

import exception.MyRuntimeException;

@Service("userService")
@Transactional(readOnly=true)
public class UserServiceImpl extends BaseServiceImpl<TUser> implements UserService {
	
	
	@Resource
	UserDao userDao;
	
	public void save(TUser user) {
		baseDao.save(user);
		
	}
	@Transactional(readOnly=false)
	public void aasaveList(List<TUser> list){
		if(!list.isEmpty()){
			for(TUser u:list){
				baseDao.save(u);
			}
		}
	}
	
	public boolean findUser(TUser user){
		String queryStr = "from TUser t where t.loginid='"+user.getLoginid()+"' and t.password='"+user.getPassword()+"'";
		List<TUser> list = baseDao.find(queryStr);
		if(list!=null&&list.isEmpty()){
			throw new MyRuntimeException("用户名或密码错误。");
		}
		return true;
	}
	public TreeObject<Integer, TMenu> getChildMenu(Integer sid) {
		HashTree<Integer, TMenu> tree = getMenuTree();
		TreeObject<Integer, TMenu> obj = new TreeObject<Integer, TMenu>(tree, sid);
		return obj;
	}
	private HashTree<Integer, TMenu> getMenuTree() {
		HashTree<Integer, TMenu> tree = new HashTree<Integer, TMenu>();
		
		List<TMenu> list = getMenu();
		for (TMenu menu : list) {
			
				tree.addNode(new TreeNode<Integer, TMenu>(menu.getSid(), menu
						.getParentSid(), menu));
			
		}
		return tree;
	}
	
	private List<TMenu> getMenu() {
		return baseDao.find("from TMenu");
	}
	public List<TMenu> getTopMenu() {
		HashTree<Integer, TMenu> tree = getMenuTree();
		return tree.getChildObject(0);
	}

}
